import { useState, useCallback, useRef, useEffect } from 'react';
import { useTVEventHandler } from 'react-native';

export interface DynamicItem {
  id: string;
  type: 'tab' | 'button' | 'card';
  onFocus?: () => void;
  onPress?: () => void;
  canFocus?: boolean;
  data?: any; // 额外数据
}

export interface DynamicGridConfig {
  tabs: DynamicItem[];
  buttons: DynamicItem[];
  cards: DynamicItem[];
  onFocusChange?: (item: DynamicItem | null) => void;
  wrapAround?: boolean;
}

export const useDynamicFocusGrid = (config: DynamicGridConfig) => {
  const [focusedItem, setFocusedItem] = useState<DynamicItem | null>(null);
  const [focusedPosition, setFocusedPosition] = useState({ x: 0, y: 0 });
  const [currentGrid, setCurrentGrid] = useState<DynamicItem[][]>([]);
  const { onFocusChange, wrapAround = true } = config;

  // 生成动态网格
  const generateGrid = useCallback((): DynamicItem[][] => {
    const { tabs, buttons, cards } = config;
    
    // 第一行：tabs + buttons
    const firstRow: DynamicItem[] = [
      ...tabs,
      ...buttons,
    ];

    // 第二行：cards
    const secondRow: DynamicItem[] = cards;

    return [firstRow, secondRow];
  }, [config]);

  // 计算坐标
  const calculateCoordinates = useCallback((grid: DynamicItem[][]): Array<DynamicItem & { x: number; y: number }> => {
    const items: Array<DynamicItem & { x: number; y: number }> = [];
    
    grid.forEach((row, y) => {
      row.forEach((item, x) => {
        items.push({
          ...item,
          x,
          y,
        });
      });
    });
    
    return items;
  }, []);

  // 更新网格
  const updateGrid = useCallback(() => {
    const newGrid = generateGrid();
    const itemsWithCoords = calculateCoordinates(newGrid);
    setCurrentGrid(newGrid);
    
    // 尝试保持当前焦点
    if (focusedItem) {
      const newFocusedItem = itemsWithCoords.find(item => item.id === focusedItem.id);
      if (newFocusedItem) {
        setFocusedItem(newFocusedItem);
        setFocusedPosition({ x: newFocusedItem.x, y: newFocusedItem.y });
        newFocusedItem.onFocus?.();
        onFocusChange?.(newFocusedItem);
        return;
      }
    }
    
    // 设置到第一个可聚焦项目
    const firstFocusable = itemsWithCoords.find(item => item.canFocus !== false);
    if (firstFocusable) {
      setFocusedItem(firstFocusable);
      setFocusedPosition({ x: firstFocusable.x, y: firstFocusable.y });
      firstFocusable.onFocus?.();
      onFocusChange?.(firstFocusable);
    }
  }, [generateGrid, calculateCoordinates, focusedItem, onFocusChange]);

  // 初始化
  useEffect(() => {
    updateGrid();
  }, [updateGrid]);

  // 查找下一个可聚焦项目
  const findNextFocusable = useCallback((direction: 'up' | 'down' | 'left' | 'right'): (DynamicItem & { x: number; y: number }) | null => {
    const itemsWithCoords = calculateCoordinates(currentGrid);
    const { x, y } = focusedPosition;
    
    let nextX = x;
    let nextY = y;
    
    switch (direction) {
      case 'up':
        nextY = wrapAround ? (y - 1 + currentGrid.length) % currentGrid.length : Math.max(0, y - 1);
        break;
      case 'down':
        nextY = wrapAround ? (y + 1) % currentGrid.length : Math.min(currentGrid.length - 1, y + 1);
        break;
      case 'left':
        nextX = wrapAround ? (x - 1 + currentGrid[y].length) % currentGrid[y].length : Math.max(0, x - 1);
        break;
      case 'right':
        nextX = wrapAround ? (x + 1) % currentGrid[y].length : Math.min(currentGrid[y].length - 1, x + 1);
        break;
    }

    const nextItem = itemsWithCoords.find(item => item.x === nextX && item.y === nextY);
    return nextItem && nextItem.canFocus !== false ? nextItem : null;
  }, [currentGrid, focusedPosition, wrapAround, calculateCoordinates]);

  // 导航
  const navigate = useCallback((direction: 'up' | 'down' | 'left' | 'right') => {
    const nextItem = findNextFocusable(direction);
    if (nextItem) {
      setFocusedItem(nextItem);
      setFocusedPosition({ x: nextItem.x, y: nextItem.y });
      nextItem.onFocus?.();
      onFocusChange?.(nextItem);
    }
  }, [findNextFocusable, onFocusChange]);

  // 处理按键事件
  useTVEventHandler((evt: any) => {
    const { eventType } = evt;
    
    switch (eventType) {
      case 'up':
        navigate('up');
        break;
      case 'down':
        navigate('down');
        break;
      case 'left':
        navigate('left');
        break;
      case 'right':
        navigate('right');
        break;
      case 'select':
      case 'enter':
        focusedItem?.onPress?.();
        break;
    }
  });

  // 检查项目是否被聚焦
  const isFocused = useCallback((item: DynamicItem) => {
    return focusedItem?.id === item.id;
  }, [focusedItem]);

  // 强制更新网格（当数据变化时调用）
  const refreshGrid = useCallback(() => {
    updateGrid();
  }, [updateGrid]);

  return {
    focusedItem,
    focusedPosition,
    currentGrid,
    navigate,
    isFocused,
    refreshGrid,
  };
}; 